from flask import Flask,request,jsonify
from flask_cors import CORS
from config import Config

from utils.acl import acl
from utils.jwttoken import token1

# 日志模块
import logging
from logging import FileHandler
import datetime



# app = Flask(__name__)

# 定义全局app
def create_app():
    app = Flask(__name__)
    with app.app_context():
        pass
    return app
app = create_app()


# 注册蓝图
from views.day01 import bp_day01
from views.company import bp_company
from views.adminuser import bp_adminuser


app.config.from_object(Config)


# 注册蓝图
app.register_blueprint(bp_day01)
app.register_blueprint(bp_company)
app.register_blueprint(bp_adminuser)



CORS(app)

@app.before_request
def before_request():
    white = ["/login","/deptlist",'/users','/upload']
    try:
        token = request.headers.get("Token")
    except:
        token = None
    if token:
        user = token1.decode_jwt(token,"123")
        if user:
            reslist = acl.get_reslist(user["id"])
            for i in reslist:
                white.append(i)
            if request.path not in white:
               return jsonify({"code":403,"msg":"fail"})
            else:
                return jsonify({"code": 40313, "msg": "no authorzation"})
        else:
            return jsonify({"code":40312,"msg":"your token has a question"})
    else:
        if request.path not in white:
            return jsonify({"code":40311,"msg":"no token"})


if __name__ == '__main__':
    filename = datetime.datetime.strftime(datetime.datetime.now(),'%Y%m')
    handler = logging.FileHandler("logs/"+filename+'.txt')
    app.logger.addHandler(handler)
    app.run()